package app.netant.excepbook.qinkan;

import org.jsoup.select.Elements;

import app.netant.NetAntBase;

public class QinKanDetail extends NetAntBase {

	private QinKanEntity entity;
	
	public QinKanDetail(String netSite) {
		super(netSite);
	}
	
	public void setEntity(QinKanEntity entity){
		this.entity = entity;
	}
	
	/**
	 * 分析类型
	 */
	public void analyseType(){
		Elements activePart = document.select(".wrap.position span a");
		if(activePart.size()>2){
			String type = activePart.get(2).text();
			System.out.println("【Type】:"+type);
			this.entity.setNovelType(type);
		}
	}
	
	public void analyseName(){
		Elements activePart = document.select(".wrap .show .showBox .detail .detail_info .detail_right h1");
		if(activePart.size()>0){
			String name = activePart.get(0).text();
			System.out.println("【Title】:"+name);
			this.entity.setNovelName(name);
			this.entity.setNovelFullName(name+".txt");
		}
	}
	
	public void analyseTags(){
		Elements activePart = document.select(".wrap .show .showBox .detail .detail_info .detail_right ul li");
		for(int i=0;i<activePart.size();i++){
			String tags = activePart.get(i).text().trim();
			int idx = tags.indexOf("：");
			if(idx>0 && idx<tags.length()-1){
				
				String tagName = tags.substring(0,idx).trim();
				String tagValue = tags.substring(idx+1).trim();
				System.out.println("【Tag】:"+tagName+"="+tagValue);
				this.entity.setTag(tagName, tagValue);
				
			}
		}
	}
	
	public void analyseMemo(){
		Elements activePart = document.select(".wrap .show .showBox.mt20 .showInfo");
		if(activePart.size()>0){
			String memo = this.getString(activePart.get(0).text());
			System.out.println("【Memo】:"+memo);
			this.entity.setNovelMemo(memo);
		}
	}
	
	public void analyseHref(){
		String href = "";
		Elements activePart = document.select(".wrap .show .showBox.mt20 .showDown ul li a.downButton");
		for(int i=0;i<activePart.size();i++){
			String txt = activePart.get(i).text().trim().toLowerCase();
			if(txt.startsWith("txt")){
				href = activePart.get(i).attr("href");
				System.out.println("【Href】:"+href);
				this.entity.setDownPath(href);
				break;
			}
		}
		
		if("".equals(href)){
			throw new RuntimeException("无法获取下载地址");
		}
	}
	
	/**
	 * 信息分析
	 */
	public void analyse(){
		
		this.analyseType();
		this.analyseName();
		this.analyseTags();
		this.analyseMemo();
		this.analyseHref();
		
		this.entity.download();
		this.entity.insert();
	}
	
	public static void main(String[] args) {
		
		QinKanDetail detail = new QinKanDetail("http://www.qinkan.net/book/33561.html");
		
		detail.analyseType();
		detail.analyseName();
		detail.analyseTags();
		detail.analyseMemo();
		detail.analyseHref();
	}

}
